package com.bootdo.backlist.service.impl;

import com.bootdo.backlist.form.NoteCodeForm;
import com.bootdo.backlist.service.YunPianService;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.enums.ResultEnum;
import com.bootdo.common.interfaces.Add;
import com.bootdo.common.interfaces.Update;
import com.bootdo.common.utils.AccountValidatorUtil;
import com.bootdo.common.utils.NoteCodeUtil;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Zengcx
 * @date 2019-04-16 10:35
 */
@Service
public class YunPianServiceImpl implements YunPianService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BootdoConfig bootdoConfig;


    @Override
    public R getCode(NoteCodeForm noteCodeForm){
        Result<SmsSingleSend> r;
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String random = NoteCodeUtil.createRandom(true, 6);
        YunpianClient clnt = new YunpianClient(bootdoConfig.getApiKey()).init();
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, noteCodeForm.getPhone());
        param.put(YunpianClient.TEXT, "【云片网】您的验证码是" + random);
//        param.put(YunpianClient.TEXT, "【云片网】您的验证码是" + random + " (20分钟内有效，如非本人操作，请忽略)");
        r = clnt.sms().single_send(param);
        if (r.getCode() == 0){
            valueOperations.set(noteCodeForm.getPhone() + "_code",random);
            redisTemplate.expire(noteCodeForm.getPhone() + "_code",20, TimeUnit.MINUTES);
        }
        return R.ok().put("data",r);
    }

    @Override
    public R valid(NoteCodeForm noteCodeForm){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String code = (String) valueOperations.get(noteCodeForm.getPhone());
        if (StringUtils.isBlank(code)){
            return R.error(ResultEnum.CODE_EXIST.getMessage());
        }
        if (!noteCodeForm.getCode().equalsIgnoreCase(code)) {
            return R.error(ResultEnum.CODE_ERROR.getMessage());
        }
        return R.ok();
    }
}
